import React, { useCallback, useEffect, useRef, useState } from 'react'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import Input from '@/components/Input'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import classNames from 'classnames'
import { useDispatch } from 'react-redux'
import { login, sendCode } from '@/store/actions/login'
import { Toast } from 'antd-mobile'
import { useHistory, useLocation } from 'react-router-dom'
export default function Login() {
  const history = useHistory()
  // 强制刷新
  const [, updateState] = useState()
  const forceUpdate = useCallback(() => updateState({}), [])
  const dispatch = useDispatch()
  const countInterval = useRef()
  const location = useLocation()
  // 倒计时
  const [count, setCount] = useState(0)
  useEffect(() => {
    clearInterval(countInterval.current)
    if (count > 0) {
      countInterval.current = setInterval(() => {
        console.log(count)
        setCount(count - 1)
      }, 1000)
    } else {
      clearInterval(countInterval.current)
    }
  }, [count])
  // 发送验证码
  const handleExtraClick = async () => {
    if (count > 0) return
    const mobile = formik.values.mobile
    if (
      !/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(
        mobile
      )
    ) {
      formik.touched.mobile = true
      formik.errors.mobile = '请正确输入手机号'
      forceUpdate()
      return
    }
    await dispatch(sendCode(mobile))
    Toast.success('发送验证码成功')
    setCount(10)
  }

  const formik = useFormik({
    initialValues: {
      mobile: '17788567811',
      code: '246810'
    },
    validationSchema: Yup.object({
      mobile: Yup.string()
        .required('请输入手机号')
        .matches(
          /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
          '请正确输入手机号'
        ),
      code: Yup.string()
        .required('请输入验证码')
        .matches(/^\d{6}$/, '请正确输入验证码')
    }),
    onSubmit: async (values) => {
      console.log('点击登录了')

      await dispatch(login(values))
      let pathname = location?.state?.pathname || '/home'

      await history.replace(pathname)
      Toast.success('登录成功')
    }
  })

  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className='content'>
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          {/* 手机号输入框 */}
          <div className='input-item'>
            <Input
              name='mobile'
              placeholder='请输入手机号'
              autoComplete='off'
              maxLength={11}
              onChange={formik.handleChange}
              value={formik.values.mobile}
              onBlur={formik.handleBlur}
            />
            {formik.touched.mobile && formik.errors.mobile ? (
              <div className='validate'>{formik.errors.mobile}</div>
            ) : null}
          </div>

          {/* 短信验证码输入框 */}
          <div className='input-item'>
            <div className='input-box'>
              <Input
                onChange={formik.handleChange}
                value={formik.values.code}
                className='input'
                name='code'
                placeholder='请输入验证码'
                maxLength={6}
                autoComplete='off'
                extra={count > 0 ? `${count}秒发送验证码` : '获取验证码'}
                onExtraClick={handleExtraClick}
                onBlur={formik.handleBlur}
              />
              {formik.touched.code && formik.errors.code ? (
                <div className='validate'>{formik.errors.code}</div>
              ) : null}
            </div>
          </div>

          {/* 登录按钮 */}
          <button
            disabled={!formik.isValid}
            type='submit'
            className={classNames(
              'login-btn',
              formik.isValid ? '' : 'disabled'
            )}>
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
